package com.oman;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class VideoFileListActivity extends ListActivity {

    public static final String TAG = "TestFileList";
    private static final int DIALOG_CHOICE = 1;
    private AlertDialog mSecletDialog;

    /**
     */
    String filepath = "/mnt/sdcard/Input";
    /**
     */
    File[] filesAllay = new File(filepath).listFiles();
    /**
     */
    List<String> nameList = new ArrayList<String>();
    Uri mUri;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate");

        nameList.add("< Go to Gallery >");
        nameList.add("<Go to VideoList>");

        if(filesAllay != null) {
            for(File file: filesAllay){
                nameList.add(file.getName());
            }
        }

        // test Oman
        long l_time = 953571;

        long totalSeconds = l_time  / 1000;

        long seconds = totalSeconds % 60;
        long minutes = (totalSeconds / 60) % 60;
        long hours   = totalSeconds / 3600;
        Log.e("Oman", hours+":"+minutes+":"+seconds);

        setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, nameList));

        /* test code */
//        int windowSize= 2560;
//        int LR2 = 64 *2;
//
//        int value = 2560- LR2;
//        int index = 202;
//        while(index <=230) {
//            Log.e("Oman", "index="+index +"value="+ value/index + "remain="+value%index);
//            index++;
//        }
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "==> onPause");
        super.onPause();
    }


    @Override
    protected void onRestart() {
        Log.d(TAG, "==> onRestart");
        super.onRestart();
    }


    @Override
    protected void onResume() {
        Log.d(TAG, "==> onResume");
//        DisplayMetrics metrics = new DisplayMetrics();
//        getWindowManager().getDefaultDisplay().getMetrics(metrics);
//        Log.d(TAG,"density : "+metrics.density);
//        Log.d(TAG,"metrics.widthPixels ="+metrics.widthPixels);
//        Log.d(TAG,"metrics.heightPixels ="+metrics.heightPixels);
//        Log.d(TAG,"metrics.xdpi ="+metrics.xdpi);
//        Log.d(TAG,"metrics.ydpi ="+metrics.ydpi);
//
//        Log.d(TAG,"this.getResources().getConfiguration() ="+this.getResources().getConfiguration());
//        Log.d(TAG, "screenLayout="+ (this.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK));

        super.onResume();
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "==> onStart");
        super.onStart();
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "==> onStop");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "==> onDestroy");

        super.onDestroy();
    }
    @Override
    protected Dialog onCreateDialog(int id) {
        // TODO Auto-generated method stub
        switch(id) {
        case DIALOG_CHOICE:
            return new AlertDialog.Builder(this)
            .setTitle("Select")
            .setItems(R.array.menu_choice, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = null;

                    switch(which) {
                    case 0:
                          intent = new Intent(Intent.ACTION_VIEW);
                          intent.setDataAndType(Uri.fromFile(new File(filepath)), "video/*");

                          startActivity(Intent.createChooser(intent, "Select player"));

                          dialog.dismiss();
                        break;
                    case 1:
                        intent = new Intent("android.intent.action.TRIM");
//                        Uri uri = Uri.fromFile(new File(filepath));
                        intent.putExtra("uri", Uri.fromFile(new File(filepath)));
                        startActivity(intent);

                        dialog.dismiss();
                        break;
                    case 2:
                        intent = new Intent("android.intent.action.VIDEOEXPAPP");
//                        Uri uri = Uri.fromFile(new File(filepath));
                        intent.putExtra("uri", Uri.fromFile(new File(filepath)));
                        startActivity(intent);

                        dialog.dismiss();
                        break;
                    }
                }
            })
            .create();

        }
//        return null;
        return super.onCreateDialog(id);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.d(TAG, "onActivityResult requestCode="+requestCode+"resultCode="+resultCode);
        if(requestCode == 300 && resultCode == RESULT_OK) {
            Uri resultUri = data.getData();
            Log.e(TAG, "path="+resultUri.getPath());
        }

        if (requestCode == 100 && resultCode == RESULT_OK) {

            if(Build.VERSION.SDK_INT >= 19) {
                Uri selectedVideo = data.getData();
                filepath = null;
                filepath= this.getPath(getApplicationContext(), selectedVideo);
                Log.e(TAG, filepath);

//                Intent intent = new Intent("android.intent.action.TRIM");
                Intent intent = new Intent("android.intent.action.TRIM_SHARE");
                Uri uri = Uri.fromFile(new File(filepath));
                intent.putExtra("uri", uri);

//                intent.putExtra("option", "PostProcessedTrim");// Trim display option.
//                intent.putExtra("outDirectory", "/storage/emulated/0/outputDir");

                startActivityForResult(intent, 300);

            } else {
                Uri selectedVideo = data.getData();

//              String filepath;
              filepath = null;
              if(getFilePathFromUri(selectedVideo) != null) {
                   filepath= getFilePathFromUri(selectedVideo);
              } else {
                  filepath = selectedVideo.getPath();
              }
//              Toast.makeText(this, "selected >>" + filepath, Toast.LENGTH_LONG).show();

              if(true) {
                  Intent intent = new Intent("android.intent.action.TRIM");
//                  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                  Intent intent = new Intent("android.intent.action.VIDEOEXPAPP");
                  Uri uri = Uri.fromFile(new File(filepath));
                  intent.putExtra("uri", uri);
                  startActivityForResult(intent, 300);
//                  startActivity(intent);
              } else {
//                  Intent intent = new Intent(Intent.ACTION_VIEW);
//                  intent.setDataAndType(Uri.fromFile(new File(filepath)), "video/*");
  //
//                  startActivity(Intent.createChooser(intent, "Select player"));
                  this.showDialog(DIALOG_CHOICE);
              }
              //showDialog(DIALOG_CHOICE);
            }
        }
    }
    static final String[] MEDIA_VIDEO_PROJECTION = new String[] {
        MediaStore.MediaColumns._ID,
        MediaStore.Video.Media.DATA
    };

    public String getFilePathFromUri(Uri uri) {
        Cursor c = getContentResolver().query(
                                uri,
                                MEDIA_VIDEO_PROJECTION,
                                null, null, null);
        if (c != null && c.moveToFirst()) {
            return c.getString(1);
        }
        return null;
    }

//
//    @Override
//    protected void onNewIntent(Intent intent) {
//        Log.d(TAG, "onNewIntent");
//        super.onNewIntent(intent);
//    }


    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        Log.d(TAG, "onListItemClick");

        if (position ==0){
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("video/*");
            startActivityForResult(intent, 100);
        } else if(position == 1){
            Intent intent= new Intent(VideoFileListActivity.this, VideoGallaryList.class);
            startActivity(intent);
        } else{

            Intent intent = new Intent("android.intent.action.TRIM_SHARE");
            //Decrease position count. because, <GO to ~> item in the listFiles
//            Intent intent = new Intent(this, VideoTextureView.class);
            position -= 2;

            if (filesAllay[position]!= null){
                Log.e(TAG, "fromFilepath"+Uri.fromFile(filesAllay[position]).getPath());
                intent.putExtra("uri",Uri.fromFile(filesAllay[position]));
                startActivityForResult(intent, 200);
            }
            else{
                Log.d(TAG, "listFiles doesn't have value");
                finish();
            }
        }
    }

    /**
     * Get a file path from a Uri. This will get the the path for Storage Access
     * Framework Documents, as well as the _data field for the MediaStore and
     * other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @author paulburke
     */
    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context The context.
     * @param uri The Uri to query.
     * @param selection (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
            String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }
}